import {defineComponent, reactive, onBeforeUnmount, provide, inject, getCurrentInstance} from 'vue'
import {designComponent} from "../../../src/use/designComponent";


interface AppRoute {
    path?: string,
    hash?: string,
    params?: string
}

//获取路由
function getRoute(): AppRoute {
    let locationHash = window.location.hash || '';
    if (locationHash.charAt(0) === '#') {
        //   去掉# 取#后面的部分
        locationHash = locationHash.slice(1)
    }
    const [path, hash] = (decodeURIComponent(locationHash)).split('#')
    return {
        path,
        hash
    }
}


export const AppNavigator =designComponent({
    name: 'app-navigator',
    provideRefer: true,
    props: {
         defaultPath: String,
    },
    setup(props, setupContext) {
        const currentRoute = getRoute();
        !currentRoute.path && (currentRoute.path = props.defaultPath);

        const ctx = getCurrentInstance()
        const state = reactive({
            route: currentRoute
        })

        const methods = {
            go(path: string) {
                window.location.hash = encodeURIComponent(path)
            },
        }

        const handler = {
            hashchange: () => {
                state.route = getRoute()
            }
        }

        const refer = {
            state,
            methods,
        };
        //
        (ctx as any)._refer = refer;

        window.addEventListener('hashchange', handler.hashchange)
        onBeforeUnmount(() => window.removeEventListener('hashchange', handler.hashchange))

        return {
            refer,
            render() {
                return setupContext.slots.default ? setupContext.slots.default() : null
            }
        }
    },
})

